package org.han.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.han.beans.PageBean;
import org.han.dao.impl.ConnDaoImpl;
import org.han.dao.impl.LogDaoImpl;
import org.han.dao.impl.UserDaoImpl;
import org.han.entity.Log;
import org.han.entity.User;
import org.han.service.ILoginBiz;
import org.han.util.JsonUtil;
import org.han.util.MD5;
import org.han.vo.LoginVo;

public class LoginBizImpl implements ILoginBiz {
	private UserDaoImpl userdao;
	private LogDaoImpl logdao;
	private ConnDaoImpl conndao;

	public ConnDaoImpl getConndao() {
		return conndao;
	}

	public void setConndao(ConnDaoImpl conndao) {
		this.conndao = conndao;
	}

	public void setLogdao(LogDaoImpl logdao) {
		this.logdao = logdao;
	}

	public LogDaoImpl getLogdao() {
		return logdao;
	}

	public void setUserdao(UserDaoImpl userdao) {
		this.userdao = userdao;
	}

	public UserDaoImpl getUserdao() {
		return userdao;
	}

	public User login(LoginVo v) throws Exception {
		User user = userdao.getUserByUname(v.getUname());
		if (user != null && MD5.getMD5(v.getPwd()).equals(user.getUPwd())) {
			addLog(new Log(user, user.getUId(), new Date()));
			return user;
		}
		return null;
	}

	public void addLog(Log l) {
		logdao.saveObject(l);
	}

	public List findConn(Integer start,Integer limit) {
		return conndao.findConn(start, limit);
	}

	public Integer getConnCount(Integer limit) {
		return conndao.getConnCount(limit);
	}

	public String getPageBean(Integer start,Integer limit) {
		Map map=new HashedMap();
		try {
			List pages = findConn(start, limit);
  			if (pages == null || pages.size() == 0) {
				map.put("result", "No Data");
				return JsonUtil.getStrByObject(map);
			}
			PageBean bean = new PageBean();
			bean.setData(pages);
			bean.setTotal(getConnCount(limit));
			bean.setCurrentPage(start/limit+1);
			bean.setNextPage(bean.getCurrentPage() + 1);
			bean.setPrevPage(bean.getCurrentPage() - 1);
			bean.setPageSize(limit);
			bean.setResult("0000");
			return JsonUtil.getStrByObject(bean);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "exception");
			return JsonUtil.getStrByObject(map);
		}
	}
}
